package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"kuafu/config"
	"kuafu/core"
	"kuafu/progress"
	"kuafu/progress/log"
	"kuafu/progress/path"
	"os"
	"os/signal"
	"syscall"
)

type LogBeatCommandFactory struct {
}

func (factory *LogBeatCommandFactory) Command() *cobra.Command {

	rootCmd := &cobra.Command{}

	//添加运行命令
	runCmd := &cobra.Command{
		Use:   "run",
		Short: "启动Kuafu脚本",
		Run: func(cmd *cobra.Command, args []string) {
			//启动
			start(cmd)
		},
	}

	//命令行所需参数
	runCmd.Flags().StringP("config", "c", "", "config (required)")
	_ = runCmd.MarkFlagRequired("config")
	rootCmd.AddCommand(runCmd)

	//添加停止命令
	rootCmd.AddCommand(&cobra.Command{
		Use:   "stop",
		Short: "停止Kuafu脚本",
		Run: func(cmd *cobra.Command, args []string) {
			//关闭
			p := new(progress.Progress)
			p.Stop()
		},
	})

	//添加获取当前目录命令
	rootCmd.AddCommand(&cobra.Command{
		Use:   "path",
		Short: "展示Kuafu脚本的当前目录路径",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Printf(path.GetCurrentDir())
		},
	})

	return rootCmd
}

func start(cmd *cobra.Command) {

	go func() {
		signalChan := make(chan os.Signal, 1)
		//监听退出信号
		signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGSEGV)
		_ = <-signalChan

		//删除pid文件
		pidManager := new(progress.PidManager)
		pidManager.RemovePid()
	}()
	p := new(progress.Progress)
	//启动
	p.Start()

	configFile, err := cmd.Flags().GetString("config")
	if err != nil {
		log.Log.Errorf("读取配置文件失败: %s", err)
		panic(err)
	}

	appConfig := &config.AppConfig{}

	err = appConfig.Load(configFile)
	if err != nil {
		log.Log.Errorf("解析配置文件失败: %s", err)
		panic(err)
	}

	logBeat := new(core.LogBeat)
	logBeat.Start(appConfig)

	//阻塞
	<-make(chan int, 1)
}
